#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <curl/curl.h>
#include "net.h"


using namespace std;

char *address = "http://www.eol.ucar.edu/cgi-bin/weather.cgi?site=fl&units=english";

static char errorBuffer[CURL_ERROR_SIZE];
static string buffer;


static int
writer(char *data,
         size_t size,
         size_t nmemb,
         std::string *writerData)
{
  if(writerData == NULL)
    return 0;
  
  writerData->append(data, size*nmemb);

  return size*nmemb;
}


float
getTempFromBuffer()
{
    int index = buffer.find("<th>Temperature</th>");
    int pointIndex = buffer.find(".", index);
    int startIndex = buffer.rfind(">", pointIndex) + 1;

    float temp =
        strtof((buffer.substr(startIndex, pointIndex+2-startIndex)).c_str(),
               NULL);

    printf("the temp is %f\n", temp);

    buffer.clear();

    return temp;
}


float
getTemp()
{
  CURL *curl;
  CURLcode res;
  
  curl = curl_easy_init();
  
  if(curl)
  {
      if(curl_easy_setopt(curl, CURLOPT_URL, address) != CURLE_OK)
      {
          printf("Error setting url [%s]\n", errorBuffer);
      }
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
//    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);  
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
    res = curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  else
  {
    printf("Error initializing library.\n");
  }

  float temp = getTempFromBuffer();

  
  return temp;
}
